package xju.rjxy.shop.web.controller;

import com.alibaba.fastjson.JSON;
import xju.rjxy.shop.common.framework.simplemvc.RequestMapping;
import xju.rjxy.shop.common.utils.JSONUtil;
import xju.rjxy.shop.common.utils.Result;
import xju.rjxy.shop.model.domain.UserGame;
import xju.rjxy.shop.model.vo.UserGameVO;
import xju.rjxy.shop.service.IUserGameService;
import xju.rjxy.shop.service.impl.UserGameServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * 用户游戏关联控制层
 */
@RequestMapping("/api/userGame")
public class UserGameController {
    private final IUserGameService userGameService = new UserGameServiceImpl();

    /**
     * 获取当前用户拥有的游戏列表，支持分页
     * GET /api/userGame/list.do?userId=xxx&page=1&size=10
     */
    @RequestMapping("/list.do")
    public void getUserGameListByUserId(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String pageStr = request.getParameter("page");
            String sizeStr = request.getParameter("size");
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            int page = pageStr != null ? Integer.parseInt(pageStr) : 1;
            int size = sizeStr != null ? Integer.parseInt(sizeStr) : 10;
            int offset = (page - 1) * size;
            // 这里假设service层方法已支持分页，否则需扩展service和mapper
            List<UserGameVO> userGameList = userGameService.getUserGameListByUserId(userId); // TODO: 实现分页
            // 简单分页（如有需要可在service/mapper层实现真正的分页）
            List<UserGameVO> pagedList = userGameList.subList(Math.min(offset, userGameList.size()), Math.min(offset + size, userGameList.size()));
            JSONUtil.printByJSON(response, Result.success(pagedList));
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/friend.do")
    public void getFriendGameList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String friendIdStr = request.getParameter("friendId");
            if (friendIdStr == null || friendIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("好友ID不能为空"));
                return;
            }
            
            Integer friendId = Integer.parseInt(friendIdStr);
            List<UserGameVO> userGameList = userGameService.getFriendGameList(friendId);
            JSONUtil.printByJSON(response, Result.success(userGameList));
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("好友ID格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/add.do")
    public void addUserGame(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取请求体
            UserGame userGame = readRequestBody(request, UserGame.class);
            
            boolean success = userGameService.addUserGame(userGame);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("游戏购买成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("游戏购买失败"));
            }
            
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/update.do")
    public void updateUserGame(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取请求体
            UserGame userGame = readRequestBody(request, UserGame.class);
            
            boolean success = userGameService.updateUserGame(userGame);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("游戏信息更新成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("游戏信息更新失败"));
            }
            
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/delete.do")
    public void deleteUserGame(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userGameIdStr = request.getParameter("userGameId");
            if (userGameIdStr == null || userGameIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户游戏ID不能为空"));
                return;
            }
            
            Integer userGameId = Integer.parseInt(userGameIdStr);
            boolean success = userGameService.deleteUserGame(userGameId);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("游戏删除成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("游戏删除失败"));
            }
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("用户游戏ID格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/check.do")
    public void checkUserGame(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String gameIdStr = request.getParameter("gameId");
            
            if (userIdStr == null || gameIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("用户ID和游戏ID不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            Integer gameId = Integer.parseInt(gameIdStr);
            
            UserGame userGame = userGameService.getUserGameByUserIdAndGameId(userId, gameId);
            JSONUtil.printByJSON(response, Result.success(userGame));
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/playTime.do")
    public void getTotalPlayTime(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            Integer totalPlayTime = userGameService.getTotalPlayTime(userId);
            JSONUtil.printByJSON(response, Result.success(totalPlayTime));
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/recent.do")
    public void getRecentPlayedGames(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String limitStr = request.getParameter("limit");
            
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            Integer limit = null;
            if (limitStr != null && !limitStr.trim().isEmpty()) {
                limit = Integer.parseInt(limitStr);
            }
            
            List<UserGameVO> recentGames = userGameService.getRecentPlayedGames(userId, limit);
            JSONUtil.printByJSON(response, Result.success(recentGames));
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    /**
     * 读取请求体并转换为指定类型
     */
    private <T> T readRequestBody(HttpServletRequest request, Class<T> clazz) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return JSON.parseObject(sb.toString(), clazz);
    }
} 